package com.cqie.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.rbac.service.ISysUserService;
import com.cqie.rbac.bo.UserBo;
import com.cqie.rbac.bo.UserUpOrAddBo;
import com.cqie.rbac.entity.SysUser;
import com.cqie.rbac.exception.BusinessException;
import com.cqie.rbac.mapper.SysRoleMapper;
import com.cqie.rbac.mapper.SysUserMapper;
import com.cqie.rbac.util.JwtUtils;
import com.cqie.rbac.util.Result;
import com.cqie.rbac.vo.UserAddOrUpdateVo;
import com.cqie.rbac.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户实体 服务实现类
 * </p>
 *
 * @author 夏兵
 * @since 2021-09-02
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public Result login(String account, String password) {
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            throw new BusinessException("5000", "账户或密码不能为空!");
        }
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getAccount, account);
        lambdaQueryWrapper.eq(SysUser::getStatus, 0);
        SysUser sysUser = sysUserMapper.selectOne(lambdaQueryWrapper);
        if (sysUser == null) {
            throw new BusinessException("4000", "账户或密码不正确!");
        }
        if (sysUser.getPassword().equals(password)) {
            String token = JwtUtils.getJwtToken(String.valueOf(sysUser.getId()), sysUser.getAccount());
            return Result.ok().message("登陆成功!").data(token);
        }
        throw new BusinessException("4000", "账户或密码不正确!");
    }

    @Override
    public Result<SysUser> pageOfUser(Integer current, Integer size, UserBo userBO) {
        Page<UserVo> page;
        if (current != null && current > 0 && size != null && size > 0) {
            page = new Page<>(current, size);
        } else {
            page = new Page<>();
        }

        QueryWrapper<UserVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(userBO.getStatus() != null, "su.status", userBO.getStatus());
        queryWrapper.like(StringUtils.isNotBlank(userBO.getName()), "su.name", userBO.getName());
        return Result.ok().data(sysUserMapper.selectPage(page, queryWrapper));
    }

    @Override
    @Transactional
    public Result changeUserStatus(List<UserBo> userBos) {
        List<SysUser> sysUsers = new ArrayList<>(userBos.size());
        userBos.forEach((userBo) -> {
            SysUser sysUser = new SysUser();
            sysUser.setId(userBo.getId());
            sysUser.setStatus(userBo.getStatus());
            sysUsers.add(sysUser);
        });
        sysUsers.forEach((sysUser) -> {
            sysUserMapper.updateById(sysUser);
        });
        return Result.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result userUpOrAdd(UserUpOrAddBo userBo) {
        if (userBo.getRoles().length < 1) {
            throw new BusinessException("5000", "用户必须有一个角色");
        }
        SysUser sysUser = new SysUser();
        sysUser.setName(userBo.getName());
        sysUser.setStatus(userBo.getStatus());
        Long id;
        if (userBo.getTag() == 1) {
            sysUser.setPassword("123456");
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getAccount, userBo.getAccount());
            if (sysUserMapper.selectOne(queryWrapper) != null) {
                throw new BusinessException("5000", "该账号已存在");
            }
            sysUser.setAccount(userBo.getAccount());
            sysUserMapper.insert(sysUser);
            id = sysUser.getId();
        } else {
            sysUser.setId(userBo.getId());
            sysUserMapper.updateById(sysUser);
            sysRoleMapper.deletUserRole(userBo.getId());
            id = userBo.getId();
        }
        for (Long i : userBo.getRoles()) {
            if (sysRoleMapper.addUserRole(id, i) == 0) {
                throw new BusinessException("5000", "添加角色失败");
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryUserById(Long id) {
        UserVo sysUser = sysUserMapper.queryUserById(id);
        return Result.ok().data(new UserAddOrUpdateVo(sysUser.getId(), sysUser.getName(),
                sysUser.getStatus(), sysUser.getRole()));
    }

    @Override
    @Transactional
    public Result multiDelUser(int[] idArray) {
        List<Integer> idList = new ArrayList<>(idArray.length);
        for (int i : idArray) {
            idList.add(i);
        }
        sysUserMapper.deleteBatchIds(idList);
        return Result.ok();
    }

    @Override
    @Transactional
    public Result multiChangeUsrStatus(List<SysUser> idAndStatus) {
        for (SysUser sysUser : idAndStatus) {
            sysUserMapper.updateById(new SysUser(sysUser.getId(), sysUser.getStatus() ^ 1));
        }
        return Result.ok();
    }
}
